<template>
  <div>
    <!--分享页面-->
    <div>
      <basic-container class="container">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>广告代理商列表</span>
          </div>
          <div class="clearfix">
            <avue-crud :option="agentOption"
                       :data="agentData"
                       :table-loading="loading"
                       :page.sync="page"
                       ref="crud"
                       @current-change="currentChange"
                       @size-change="sizeChange"
                       @refresh-change="refreshChange"
                       @on-load="onload"
            >
              <!-- 状态-->
              <template slot-scope="scope" slot="status">
                <el-select id="id-business-components-offershareoutside-statusChange"
                           v-model="scope.row.status" size="mini" @change="statusChange($event,scope.row)">
                  <el-option v-for="item in statusList" :key="item.dictKey" :label="item.dictValue"
                             :value="item.dictKey*1"></el-option>
                </el-select>
              </template>
              <!-- 投放信息-->
              <template slot-scope="scope" slot="info">
                <div>
                  <el-tag size="small" type="success"  v-if="scope.row.iosNation !== '' && scope.row.iosPlatform !== ''">IOS:</el-tag>
                  <el-tag size="small" type="info" style="margin-left: 2px" v-if="scope.row.iosNation !== ''">
                    {{ controlWord(nationWord(scope.row.iosNation)) }}
                  </el-tag>
                  <el-tag size="small" type="warning" style="margin-left: 2px" v-if="scope.row.iosPlatform !== ''">
                    {{ controlWord(scope.row.iosPlatform) }}
                  </el-tag>
                </div>
                <div class="runInfoBorder">
                  <el-tag size="small" type="success" v-if="scope.row.androidNation !== '' && scope.row.androidPlatform !== ''">Android:</el-tag>
                  <el-tag size="small" type="info" style="margin-left: 2px" v-if="scope.row.androidNation !== ''">
                    {{ controlWord(nationWord(scope.row.androidNation)) }}
                  </el-tag>
                  <el-tag size="small" type="warning" style="margin-left: 2px" v-if="scope.row.androidPlatform !== ''">
                    {{ controlWord(scope.row.androidPlatform) }}
                  </el-tag>
                </div>
                <div class="runInfoBorder">
                  <el-tag size="small" type="success" v-if="scope.row.websiteNation !== '' && scope.row.websitePlatform !== ''">Website:</el-tag>
                  <el-tag size="small" type="info" style="margin-left: 2px" v-if="scope.row.websiteNation !== ''">
                    {{ controlWord(nationWord(scope.row.websiteNation)) }}
                  </el-tag>
                  <el-tag size="small" type="warning" style="margin-left: 2px" v-if="scope.row.websitePlatform !== ''">
                    {{ controlWord(scope.row.websitePlatform) }}
                  </el-tag>
                </div>
              </template>
              <template slot-scope="scope" slot="accounts">
                <el-popover placement="left" width="400" trigger="click" style="background-color: #a6a9ad">
                  <div v-for="(item,index) in scope.row.accounts" :key="index" style="margin-top: 5px">
                    <div style="color: #4093ff">账户名 : {{ item.split('-')[0] }}</div>
                    <div>ID : {{ item.split('-')[1] }}</div>
                  </div>
                  <div slot="reference" style="color: #409eff;cursor: pointer">{{ scope.row.accounts.length }}</div>
                </el-popover>
              </template>
              <template slot="menuLeft">
                <el-button id="id-business-components-offershareoutside-handleAdd"
                           size="small" icon="el-icon-plus" type="primary" plain @click="handleAdd" v-if="!openCheck">
                  新 增
                </el-button>
              </template>
              <template slot-scope="{type,size,row}" slot="menu">
<!--                <el-button v-if="!openCheck" icon="el-icon-delete" :size="size" :type="type" @click="handleDel(row)">删-->
<!--                  除-->
<!--                </el-button>-->
                <el-button id="id-business-components-offershareoutside-handleCheck" icon="el-icon-view"
                           :size="size" :type="type" @click="handleCheck(row)">详 情</el-button>
              </template>
            </avue-crud>
          </div>
        </el-card>
      </basic-container>
    </div>
    <!-- 新增弹窗 -->
    <el-drawer :title="title" :visible.sync="addAgent" size="80%" direction="rtl" :modal-append-to-body="false"
               :append-to-body="true" :before-close="handleAddClose"
               :close-on-click-modal="false">
      <div  class="center_form">
      <el-form ref="addForm" :model="form" :rules="rules" label-width="100px" v-loading="addloading">
        <el-form-item v-if="title === '添加代理商'" label="代理商:" prop="tenantId">
          <el-select id="id-business-components-offershareoutside-form-tenantId" v-model="form.tenantId" size="mini" clearable filterable style="width: 660px;">
            <el-option v-for="item in agentList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="title === '查看代理商详情'" prop="details">
          <div class="check">
            <div>公司名称 : {{ check.name }}</div>
            <div>手机号 : {{ check.phone }}</div>
            <div>邮箱 : {{ check.email }}</div>
            <div>地址 : {{ check.address }}</div>
            <div style="width: 100%">备注 :{{ check.remark }}</div>
          </div>
        </el-form-item>
        <el-form-item label="投放信息:" prop="platformInfo">
          <div class="platformInfo_item">
            <el-checkbox v-model="ios" :disabled="judge('IOS')" @change="getSystemUrl($event,'IOS')">IOS</el-checkbox>
            <el-form-item v-if="form.ios" label="投放地区:" prop="iosNation">
              <el-select id="id-business-components-offershareoutside-form-iosNation" v-model="form.iosNation" size="mini" filterable multiple>
                <el-option v-for="item in countryIosList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.ios" label="媒体:" prop="iosPlatform">
              <el-select id="id-business-components-offershareoutside-form-iosPlatform" v-model="form.iosPlatform" size="mini" filterable multiple>
                <el-option v-for="item in platformIosList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="platformInfo_item">
            <el-checkbox v-model="android" :disabled="judge('Android')" @change="getSystemUrl($event,'Android')">
              Android
            </el-checkbox>
            <el-form-item v-if="form.android" label="投放地区:" prop="androidNation">
              <el-select id="id-business-components-offershareoutside-form-androidNation" v-model="form.androidNation" size="mini" filterable multiple>
                <el-option v-for="item in countryAndroidList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.android" label="媒体:" prop="androidPlatform">
              <el-select id="id-business-components-offershareoutside-form-androidPlatform" v-model="form.androidPlatform" size="mini" filterable multiple>
                <el-option v-for="item in platformAndroidList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="platformInfo_item">
            <el-checkbox v-model="website" :disabled="judge('Website')" @change="getSystemUrl($event,'Website')">
              Website
            </el-checkbox>
            <el-form-item v-if="form.website" label="投放地区:" prop="websiteNation">
              <el-select id="id-business-components-offershareoutside-form-websiteNation" v-model="form.websiteNation" size="mini" filterable multiple>
                <el-option v-for="item in countryWebsiteList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.website" label="媒体:" prop="websitePlatform">
              <el-select id="id-business-components-offershareoutside-form-websitePlatform" v-model="form.websitePlatform" size="mini" filterable multiple>
                <el-option v-for="item in platformWebsiteList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="账户信息:" prop="accounts">
          <div style="overflow-y: auto;max-height: 200px">
            <div v-for="(item,index) in form.accounts" :key="index">
              <div style="display: flex">
                <el-form-item v-if="item.name" style="width: 280px; margin-right: 30px" prop="id_label">
                  {{ item.name }}
                </el-form-item>
                <el-form-item v-if="!item.name" prop="accounts.id" :rules="rules['accounts.id']">
                  <el-select id="id-business-components-offershareoutside-id" v-model="item.id"
                             size="mini" style="width: 280px; margin-right: 30px" filterable clearable>
                    <el-option v-for="it in originalAccountList" :key="it.value" :label="it.label"
                               :disabled="changeAccountList(it.value)" :value="it.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="accounts.permission" :rules="rules['accounts.permission']">
                  <el-select id="id-business-components-offershareoutside-permission"
                             v-model="item.permission" size="mini" style="margin-right: 30px" multiple collapse-tags>
                    <el-option v-for="it in permissionList" :key="it.value" :label="it.label"
                               :value="it.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-button id="id-business-components-offershareoutside-addAccounts"  @click="addAccounts" icon="el-icon-plus" size="mini"></el-button>
                <el-button id="id-business-components-offershareoutside-deleteAccounts"  @click="deleteAccounts(index)" icon="el-icon-minus" size="mini"></el-button>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button id="id-business-components-offershareoutside-handleAddClose"  @click="handleAddClose" size="mini">取 消</el-button>
          <el-button id="id-business-components-offershareoutside-confirm"  @click="confirm" type="primary" size="mini" v-if="!openCheck" :disabled="shareDisable">确认分享</el-button>
        </el-form-item>
      </el-form>
      </div>
    </el-drawer>

    <!-- 详情弹窗 -->
  </div>
</template>
<script>
import {
  getSelectAgency,
  getOfferType,
  getOfferNation,
  getOfferPlatform,
  getExternalAccount,
  shareToAgency,
  getOfferList,
  getOutList,
  externalStatus,
  getShareAccount,
  getByAgency
} from '@/api/business/share'
import {getSysDictList} from '@/api/system/dict'

let offerlist = []
export default {
  name: 'offerShareOutside',
  props: {
    offerId: {
      type: String
    },
    openCheck: {
      type: Boolean
    },
  },
  data() {
    /**
     * 验证
     */
    var checkPlatformInfo = (rule, value, callback) => {
      if (!this.ios && !this.android && !this.website) {
        return callback(new Error('请选择投放信息'))
      } else {
        callback();
      }
    }

    var checkIosNation = (rule, value, callback) => {
      if (this.ios) {
        if (!value.length > 0) {
          return callback(new Error('请选择ios投放投放地区'))
        } else {
          callback();
        }
      } else {
        callback();
      }
    }

    var checkIosPlatform = (rule, value, callback) => {
      if (this.ios) {
        if (!value.length > 0) {
          return callback(new Error('请选择ios媒体'))
        } else {
          callback();
        }
      } else {
        callback();
      }
    }

    var checkAndroidNation = (rule, value, callback) => {
      if (this.android) {
        if (value.length === 0) {
          return callback(new Error('请选择android投放投放地区'))
        } else {
          callback();
        }
      } else {
        callback();
      }
    }

    var checkAndroidPlatform = (rule, value, callback) => {
      if (this.android) {
        if (!value.length > 0) {
          return callback(new Error('请选择android媒体'))
        } else {
          callback();
        }
      } else {
        callback();
      }
    }

    var checkWebsiteNation = (rule, value, callback) => {
      if (this.website) {
        if (value.length === 0) {
          return callback(new Error('请选择website投放投放地区'))
        } else {
          callback();
        }
      } else {
        callback();
      }
    }

    var checkWebsitePlatform = (rule, value, callback) => {
      if (this.website) {
        if (!value.length > 0) {
          return callback(new Error('请选择website媒体'))
        } else {
          callback();
        }
      } else {
        callback();
      }
    }

    return {
      addloading:false,
      title: '',
      ios: false,//新增是否选择ios
      android: false,//新增是否选择android
      website:false,
      addAgent: false,//添加弹窗
      agentData: [],//列表数据
      loading: false,
      statusList: [],//状态列表
      nationList: [],//投放地区列表
      form: {},
      check: {},//代理商详细信息
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },//列表参数
      agentOption: {
        editBtn: false,
        addBtn: false,
        delBtn: false,
        refreshBtn: true,
        columnBtn: false,
        menuWidth: 80,
        menu: true,
        column: [
          {
            label: '代理商名称',
            prop: 'tenantName'
          }, {
            label: '邮箱',
            prop: 'email'
          }, {
            label: '状态',
            prop: 'status',
            width: 120
          }, {
            label: '投放信息',
            prop: 'info',
            width: 350
          }, {
            label: '账户信息',
            prop: 'accounts',
            width: 120
          }
        ],
      },//列表配置
      agentList: [],//代理商列表
      countryAndroidList: [],//android投放地区列表
      platformAndroidList: [],//android平台列表
      countryIosList: [],//ios投放地区列表
      platformIosList: [],//ios平台列表
      countryWebsiteList:[],
      platformWebsiteList:[],
      permissionList: [
        {value: '1', label: '含花费'},
        {value: '2', label: '含点击'},
        {value: '3', label: '含曝光'},
        {value: '4', label: '含安装'}
      ],//权限列表
      typeList: [],//投放系统信息
      originalAccountList: [],//原始账户列表
      query: {
        offerId: ''
      },
      shareDisable:false,//不可分享
      rules: {
        'tenantId': [{required: true, message: '请选择代理商', trigger: 'change'}],
        'platformInfo': [{required: true, validator: checkPlatformInfo, trigger: 'change'}],
        'iosNation': [{required: true, validator: checkIosNation, trigger: 'change'}],
        'iosPlatform': [{required: true, validator: checkIosPlatform, trigger: 'change'}],
        'androidNation': [{required: true, validator: checkAndroidNation, trigger: 'change'}],
        'androidPlatform': [{required: true, validator: checkAndroidPlatform, trigger: 'change'}],
        'websiteNation': [{required: true, validator: checkWebsiteNation, trigger: 'change'}],
        'websitePlatform': [{required: true, validator: checkWebsitePlatform, trigger: 'change'}],
        // 'accounts.id': [{required: true, message: '请选择账户', trigger: 'change'}],
        // 'accounts.permission': [{required: true, message: '请选择权限', trigger: 'change'}]
      }
    }
  },
  watch: {
    offerId: {
      deep: true,
      handler(val) {
        if (val) {
          this.query.offerId = this.offerId
          this.onload(this.page)
        }
      }
    }
  },
  created() {
    this.statusList = [{dictValue: "停止", dictKey: '1'}, {dictValue: "活跃", dictKey: '0'}]
    getOfferList().then(res => {
      offerlist = res.data.data
    })
    this.query.offerId = this.offerId
    getSysDictList("nation").then(map => {
      this.nationList = map['nation']
    })
  },
  methods: {
    refreshChange() {
      this.onload(this.page, this.query);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     *  控制投放信息的字数
     * **/
    controlWord(val) {
      if (val.length > 10) {
        return val.substring(0, 9) + ' ...'
      }
      return val
    },
    /**
     * 修改投放地区
     */
    nationWord(val) {
      val = val.split(',')
      let list = []
      val.map(item => {
        for (let index in this.nationList) {
          if (item === this.nationList[index].dictKey) {
            list.push(this.nationList[index].dictValue)
          }
        }
      })
      return list.join(',')
    },
    /**
     * 修改列表中状态
     * **/
    statusChange(val, row) {
      externalStatus(row.agencyTenantId, this.offerId, val).then(res =>{
        if(res){
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
        }
      })
    },
    /**
     * 加载列表
     **/
    onload(page, params = {}) {
      this.query.offerId = this.offerId
      this.loading = true
      this.$nextTick(() => {
        getOutList(
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.query),
        ).then(res => {
          this.agentData = res.data.data.records
          this.page.total = res.data.data.total
          this.loading = false
        }, error => {
          if (error) {
            this.agentData = []
            this.loading = false
          }
        })
      })

    },
    /**
     * 删除列表项
     */
    handleDel() {

    },
    /**
     * 查看列表详情
     */
    handleCheck(row) {
      this.title = '查看代理商详情'
      this.reset()
      this.addAgent = true
      this.getInfo(() => {
        if (row.iosNation !== '' && row.iosPlatform !== '') {
          this.ios = true
          this.typeList.map(item => {
            if (item.label === 'IOS') {
              this.form.ios = true
            }
          })
        }
        if (row.androidNation !== '' && row.androidPlatform !== '') {
          this.android = true
          this.typeList.map(item => {
            if (item.label === 'Android') {
              this.form.android = true
            }
          })
        }
        if (row.websiteNation !== '' && row.websitePlatform !== '') {
          this.website = true
          this.typeList.map(item => {
            if (item.label === 'Website') {
              this.form.website = true
            }
          })
        }
      })
      if(row.status === 1){
        this.shareDisable = true
      }
      getShareAccount(row.agencyTenantId, this.offerId).then(res => {
        this.form.accounts = res.data.data.length > 0 ? res.data.data : this.form.accounts
        this.form.accounts.map(item => {
            item.permission = item.permission.length > 0 ? item.permission.split(',') : ''
        });
      })
      this.form.androidNation = row.androidNation ? row.androidNation.split(',') : null
      this.form.androidPlatform = row.androidPlatform ? row.androidPlatform.split(',') : null
      this.form.iosNation = row.iosNation ? row.iosNation.split(',') : null
      this.form.iosPlatform = row.iosPlatform ? row.iosPlatform.split(',') : null
      this.form.websiteNation = row.websiteNation ? row.websiteNation.split(',') : null
      this.form.websitePlatform = row.websitePlatform ? row.websitePlatform.split(',') : null
      this.form.offerId = this.offerId
      this.form.tenantId = row.agencyTenantId
      getByAgency(this.form.tenantId).then(res => {
        this.check = res.data.data
      })
    },
    /**
     * 获取信息
     */
    getInfo(callback) {
      //获取代理商列表
      getSelectAgency(this.offerId).then(res => {
        this.agentList = res.data.data
      })
      //获取offer订单信息
      getOfferType(this.offerId).then(res => {
        this.typeList = res.data.data
        this.typeList.map(item => {
          if (item.label === 'IOS') {
            this.countryIosList = item.nation
            this.platformIosList = item.platform
          }
          if (item.label === 'Android') {
            this.countryAndroidList = item.nation
            this.platformAndroidList = item.platform
          }
          if(item.label === 'Website'){
            this.countryWebsiteList = item.nation
            this.platformWebsiteList = item.platform
          }
        })
        if (this.title === '查看代理商详情') {
          callback()
        }
      })
      //获取账户列表
      getExternalAccount(this.offerId).then(res => {
        this.originalAccountList = res.data.data
      })

    },
    /**
     * 添加代理商
     */
    handleAdd() {
      this.reset()
      this.getInfo()
      this.title = '添加代理商'
      this.addAgent = true
    },
    /**
     * 判断系统是否可以选中
     */
    judge(system) {
      let is = true
      this.typeList.map(item => {
        if (item.label === system) {
          is = false
        }
      })
      return is
    },
    /**
     * 获取选中系统的URL
     */
    getSystemUrl(el, system) {
      if (el) {
        this.typeList.map(item => {
          if (system === item.label) {
            if (system === 'IOS') {
              this.form.ios = true
            }
            if (system === 'Android') {
             this.form.android = true
            }
            if(system === 'Website'){
              this.form.website = true
            }
          }
        })
      } else {
        if (system === 'IOS') {
          this.form.ios = null
          this.form.iosPlatform = null
          this.form.iosNation = null
        }
        if (system === 'Android') {
          this.form.android = null
          this.form.androidNation = null
          this.form.androidPlatform = null
        }
        if(system === 'Website'){
          this.form.website = null
          this.form.websiteNation = null
          this.form.websitePlatform = null
        }
      }
    },
    /**
     * 修改账户列表
     */
    changeAccountList(val) {
      let isDisable
      // let chooseList = []
      this.form.accounts.map(item => {
        if (val === item.id) {
          isDisable = true
        }
      })
      return isDisable
    },
    /**
     * 添加账户
     */
    addAccounts() {
      this.form.accounts.push({
        id: null,
        permission: ['1','2','3','4']
      })
    },
    /**
     * 减少账户
     */
    deleteAccounts(index) {
      if (this.form.accounts.length > 1) {
        if (this.form.accounts[index].name) {
          let item = {
            label: this.form.accounts[index].name,
            value: this.form.accounts[index].id
          }
          this.originalAccountList.push(item)
        }
        this.form.accounts.splice(index, 1)
      }
    },
    /**
     * 确认弹窗
     */
    confirm() {

      let offerName
      let agentName
      offerlist.map(item => {
        if (item.id === this.offerId) {
          offerName = item.name
        }
      })
      this.agentList.map(item => {
        if (item.value === this.form.tenantId) {
          agentName = item.label
        }
      })
      if(this.title === '查看代理商详情'){
        agentName = this.check.name
      }
      this.$confirm('点击确认分享，提示“你确认要把 "' + offerName + '" 订单分享给 "' + agentName + ' " 代理商吗?”', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitAdd()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消新增'
        });
      });
    },
    /**
     * 确认分享
     */
    submitAdd() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.form.accounts.map(item => {
            item.permission = item.permission.join(',')
          });
          let data = {
            androidNation: this.form.androidNation ? this.form.androidNation.join(',') : null,
            androidPlatform: this.form.androidPlatform ? this.form.androidPlatform.join(',') : null,
            iosNation: this.form.iosNation ? this.form.iosNation.join(',') : null,
            iosPlatform: this.form.iosNation ? this.form.iosPlatform.join(',') : null,
            websiteNation: this.form.websiteNation ? this.form.websiteNation.join(','):null,
            websitePlatform: this.form.websitePlatform ? this.form.websitePlatform.join(','):null,
            offerId: this.offerId,
            tenantId: this.form.tenantId,
            accounts: this.form.accounts,
          }
          this.addloading = true
          shareToAgency(data).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '新增成功!'
              });
              this.addloading = false
              this.handleAddClose()
            }
          },error => {
            if(error)
              this.addloading = false
              this.handleAddClose()
          })
        }
      })

    },
    /**
     * 重置form表单
     */
    reset(){
      this.form = {
        ios:'',
        android:'',
        website:'',
        tenantId: null,
        offerId: null,
        iosNation: null,
        iosPlatform: null,
        androidNation: null,
        androidPlatform: null,
        websiteNation:null,
        websitePlatform:null,
        accounts: [
          {id: null, permission: ['1','2','3','4']}
        ]
      }
    },

    /**
     * 关闭添加代理商弹窗
     */
    handleAddClose() {
      this.ios = false
      this.android = false
      this.website = false
      this.addAgent = false
      this.onload(this.page)
      this.shareDisable = false
    }
  }
}
</script>
<style lang="scss">
.container {
  margin: 15px;
}

.runInfoBorder {
  margin-top: 2px;
}

.platformInfo_item {
  padding-left: 5px;
  display: flex;

  .item {
    margin-left: 30px;
  }

  .itemSpan {
    margin-right: 10px;
  }

}

.check {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  div {
    width: 48%;
    margin-top: 10px;
  }
}
.center_form {
  margin-top: 20px;
  display:flex;
  justify-content: center;
}
</style>
